package gw.com.android.ui.home;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.presenter.FMPresenter;
import gw.com.android.presenter.http.FMRequest;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.views.CornerEdgeTextView;
import gw.com.android.ui.views.WaveView;
import gw.com.android.utils.PackStatis;
import www.com.library.interfaces.ReqCallBack;

/**
 * @author jett
 * @since 2017-12-05.
 */
public class FMActivity extends BaseActivity {

    @BindView(R.id.fm_wv)
    WaveView wv;
    @BindView(R.id.fm_title)
    TextView tvTitle;
    @BindView(R.id.fm_time)
    TextView tvTime;
    @BindView(R.id.fm_tag)
    CornerEdgeTextView tvTag;
    @BindView(R.id.fm_progress_time)
    TextView tvProgressTime;
    @BindView(R.id.fm_total_time)
    TextView tvTotalTime;
    @BindView(R.id.fm_content)
    TextView tvContent;
    @BindView(R.id.progressBar_video)
    SeekBar sbProgress;
    @BindView(R.id.fm_play)
    ImageView ivPlay;
    @BindView(R.id.rl_container)
    ViewGroup rlContainer;
    @BindView(R.id.fl_error)
    ViewGroup flError;

    private FMPresenter.FMListener fmListener;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_fm;
    }

    @Override
    protected void initLayoutView() {
        wv.setWaveColor(0xFFf8a916);
        fmListener = new FMPresenter.SimpleListener() {
            @Override
            public void onPrepared() {
                onPreparedPlay();
            }

            @Override
            public void onStarted() {
                onStartPlay();
            }

            @Override
            public void onPaused() {
                onPausePlay();
            }

            @Override
            public void onCompleted() {
                onCompletedPlay();
            }

            @Override
            public void onReset() {
                onResetPlay();
            }

            @Override
            public void onPlaying(int progress) {
                onProgressPlay(progress);
            }
        };
        sbProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    FMPresenter.getInstance().seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        FMPresenter.getInstance().addListener(fmListener);
        int duration = FMPresenter.getInstance().getDuration();
        int currPosition = FMPresenter.getInstance().getCurrentPosition();
        boolean playing = FMPresenter.getInstance().isPlaying();
        tvProgressTime.setText(formatMillisecond(currPosition));
        tvTotalTime.setText(formatMillisecond(duration));
        sbProgress.setMax(duration);
        sbProgress.setProgress(currPosition);
        if (playing) {
            onStartPlay();
        } else {
            onPausePlay();
        }
    }

    @Override
    protected void initViewData() {
        FMRequest request = new FMRequest();
        FMRequest.DetailData data = request.fetchLocal();
        if (data != null) {
            refreshUi(data, true);
        }
        request.call(new ReqCallBack<FMRequest.DetailData>() {
            @Override
            public void onReqSuccess(FMRequest.DetailData result) {
                refreshUi(result, false);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                onError();
            }
        });
    }

    private void onPreparedPlay() {
        int duration = FMPresenter.getInstance().getDuration();
        int currPosition = FMPresenter.getInstance().getCurrentPosition();
        sbProgress.setMax(duration);
        sbProgress.setProgress(currPosition);
        tvProgressTime.setText(formatMillisecond(currPosition));
        tvTotalTime.setText(formatMillisecond(duration));
    }

    private void onStartPlay() {
        ivPlay.setImageResource(R.mipmap.a_fm_pause);
        wv.startWave();
    }

    private void onPausePlay() {
        ivPlay.setImageResource(R.mipmap.a_fm_play);
        wv.stopWave();
    }

    private void onCompletedPlay() {
        tvProgressTime.setText(formatMillisecond(0));
        ivPlay.setImageResource(R.mipmap.a_fm_play);
        sbProgress.setProgress(0);
        FMPresenter.getInstance().preparePlayer();
        PackStatis.getToService("clickradioover", "HomeFM", null, null);
    }

    private void onResetPlay() {
        tvProgressTime.setText(formatMillisecond(0));
        tvTotalTime.setText(formatMillisecond(0));
        ivPlay.setImageResource(R.mipmap.a_fm_play);
        sbProgress.setProgress(0);
    }

    private void onProgressPlay(int currPosition) {
        sbProgress.setProgress(currPosition);
        tvProgressTime.setText(formatMillisecond(currPosition));
    }

    private String formatMillisecond(int millisecond) {
        if (millisecond <= 0) {
            return "00:00";
        }
        int second = Math.round(millisecond * 1F / 1000);
        int minute = second / 60;
        second = second - minute * 60;
        StringBuilder sb = new StringBuilder();
        if (minute <= 9) {
            sb.append("0");
        }
        sb.append(minute);
        sb.append(":");
        if (second <= 9) {
            sb.append("0");
        }
        sb.append(second);
        return sb.toString();
    }

    private void refreshUi(FMRequest.DetailData data, boolean local) {
        if (data == null) {
            if (!local) {
                onError();
            }
            return;
        }
        flError.setVisibility(View.GONE);
        rlContainer.setVisibility(View.VISIBLE);

        tvTitle.setText(data.title);
        tvTime.setText(formatTime(data.createTime));
        setTagText(data.tag);
        if (data.content != null) {
            tvContent.setText(data.content);
        }
        if (!TextUtils.isEmpty(data.audioUrl)){
        FMPresenter.getInstance().load(data.audioUrl);}
        //FMPresenter.getInstance().load("https://vod.hx9999.com/info/n1220.mp3");
    }

    private void setTagText(String text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        tvTag.setVisibility(View.VISIBLE);
        tvTag.setText(text);
        if (text.contains("利多")) {
            tvTag.setTextColor(0xFFFD383F);
        } else if (text.contains("利空")) {
            tvTag.setTextColor(0xFF2BBB72);
        } else if (text.contains("观望")) {
            tvTag.setTextColor(0xFFF88116);
        } else {
            tvTag.setVisibility(View.GONE);
        }
    }

    private void onError() {
        rlContainer.setVisibility(View.GONE);
        flError.setVisibility(View.VISIBLE);
    }

    private CharSequence extractAudio(String content) {
        /*if (TextUtils.isEmpty(content)) {
            return content;
        }
        //   {audio alt=&quot;&quot;}http://cms.beta.5kwords.com:80/jinDao/u/cms//beta/201712/081442408mue.mp3{/audio}
        Matcher matcher = Pattern.compile("\\{audio[^}]*\\}.+\\{/audio\\}").matcher(content);
        if (matcher.find()) {
            String group = matcher.group();
            if (group != null) {
                String result = group.replaceAll("\\{/?audio[^}]*\\}", "");
                if (result.startsWith("http")) {
                    audioUrl = result;
                }
                String str = content.replace(group, "");
                return str.replaceAll("[\n]{2,}&", "\n\n");
            }
        }*/
        return content;
    }

    private String formatTime(String timeString) {
        if (!TextUtils.isEmpty(timeString)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            //format.setTimeZone(TimeZone.getTimeZone("UTC"));
            try {
                Date date = format.parse(timeString);
                return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(date);
            } catch (ParseException ignore) {
            }
        }
        return "";
    }

    @OnClick(R.id.fm_play)
    void play() {
        PackStatis.getToService("clickradio", "HomeFM", null, null);
        boolean playing = FMPresenter.getInstance().isPlaying();
        if (playing) {
            FMPresenter.getInstance().pause();
        } else {
            FMPresenter.getInstance().start();
        }
    }

    @OnClick(R.id.fm_back)
    void back() {
        finish();
    }

    @OnClick(R.id.fm_share)
    void share() {
    }

    @Override
    protected void onDestroy() {
        FMPresenter.getInstance().removeListener(fmListener);
        if (!FMPresenter.getInstance().isPlaying()) {
            FMPresenter.getInstance().release();
        }
        super.onDestroy();
    }
}
